package com.jianan.mis.app.overseastudy;

import static com.jianan.mis.util.ui.table.TableCreator.createSortedTableColumn;
import static com.jianan.mis.util.ui.table.TableCreator.createTableColumn;

import java.math.BigDecimal;
import java.text.Collator;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.part.ViewPart;

import com.jianan.mis.data.cache.CountryCache;
import com.jianan.mis.data.dao.base.PageControl;
import com.jianan.mis.data.domain.Country;
import com.jianan.mis.data.domain.Department;
import com.jianan.mis.data.domain.OsDepartmentContract;
import com.jianan.mis.service.DepartmentService;
import com.jianan.mis.service.OsDepartmentContractService;
import com.jianan.mis.sys.IImageKeys;
import com.jianan.mis.sys.IMessageKeys;
import com.jianan.mis.sys.ImageManager;
import com.jianan.mis.sys.ResourceManager;
import com.jianan.mis.sys.SpringBeanFactory;
import com.jianan.mis.util.StringUtils;
import com.jianan.mis.util.ui.table.AbstractInvertableTableSorter;

public class OsDepartmentContractArchiveView extends ViewPart {

	private Label lblResult;
	private Label lblPage;
	private Combo comboDepartment;
	private Text txtContractNo;
	private Combo comboCountry;
	private Text txtStudentName;
	
	class TableLabelProvider extends LabelProvider implements ITableLabelProvider {
		public String getColumnText(Object element, int columnIndex) {
			OsDepartmentContract osDepartmentContract = (OsDepartmentContract) element;
			String text = contracts.getColumn(columnIndex).getText();
			if (text.equals(CONTRACT_ID)) {
				return osDepartmentContract.getId().toString();
			} else if (text.equals(CONTRACT_NO)) {
				return osDepartmentContract.getContractNo();
			} else if (text.equals(STUDENT_NAME)) {
				return osDepartmentContract.getName();
			} else if (text.equals(COUNTRY_NAME)) {
				return osDepartmentContract.getCountry().getName();
			} else if (text.equals(DEPARTMENT_NAME)) {
				return osDepartmentContract.getDepartment().getName();
			} else if (text.equals(SIGNUP_SUM)) {
				return "￥" + osDepartmentContract.getSignupSum().setScale(2, BigDecimal.ROUND_HALF_UP).toString();
			} else if (text.equals(LICENSE)) {
				if (osDepartmentContract.isLicense())
					return "是";
				else
					return "否";
			} else if (text.equals(SIGNUP_DATE)) {
				return dateFormat.format(osDepartmentContract.getSignupDate());
			} else {
				return null;
			}
		}
		public Image getColumnImage(Object element, int columnIndex) {
			return null;
		}
	}
	class ContentProvider implements IStructuredContentProvider {
		public Object[] getElements(Object inputElement) {
			return ((List) inputElement).toArray();
		}
		public void dispose() {
		}
		public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
		}
	}
	public static final String ID = "com.jianan.mis.app.overseastudy.OsDepartmentContractArchiveView"; //$NON-NLS-1$

	private TableViewer contractTableViewer;
	private Table contracts;
	final private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日");
	final private int PAGE_SIZE = 15;
	private PageControl pageControl;
	private Map conditions;
	
	/**
	 * Create contents of the view part
	 * @param parent
	 */
	@Override
	public void createPartControl(Composite parent) {
		final FillLayout fillLayout = new FillLayout();
		fillLayout.marginWidth = 10;
		fillLayout.marginHeight = 10;
		parent.setLayout(fillLayout);
		Composite container = new Composite(parent, SWT.NONE);
		final GridLayout gridLayout = new GridLayout();
		gridLayout.makeColumnsEqualWidth = true;
		gridLayout.numColumns = 4;
		container.setLayout(gridLayout);

		final Label label = new Label(container, SWT.NONE);
		label.setFont(ResourceManager.getFont("", 10, SWT.BOLD));
		label.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 4, 1));
		label.setText("查询条件:");

		final Label label_1 = new Label(container, SWT.NONE);
		label_1.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
		label_1.setText("学生姓名:");

		txtStudentName = new Text(container, SWT.BORDER);
		final GridData gd_txtStudentName = new GridData(SWT.LEFT, SWT.CENTER, true, false);
		txtStudentName.setLayoutData(gd_txtStudentName);

		final Label label_2 = new Label(container, SWT.NONE);
		label_2.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
		label_2.setText("咨询国家:");

		comboCountry = new Combo(container, SWT.READ_ONLY);
		final GridData gd_comboCountry = new GridData(SWT.LEFT, SWT.CENTER, true, false);
		comboCountry.setLayoutData(gd_comboCountry);

		final Label label_3 = new Label(container, SWT.NONE);
		label_3.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
		label_3.setText("合同号:");

		txtContractNo = new Text(container, SWT.BORDER);
		final GridData gd_txtContractNo = new GridData(SWT.LEFT, SWT.CENTER, true, false);
		gd_txtContractNo.widthHint = 150;
		txtContractNo.setLayoutData(gd_txtContractNo);

		final Label label_4 = new Label(container, SWT.NONE);
		label_4.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
		label_4.setText("部门:");

		comboDepartment = new Combo(container, SWT.READ_ONLY);
		final GridData gd_comboDepartment = new GridData(SWT.LEFT, SWT.CENTER, true, false);
		comboDepartment.setLayoutData(gd_comboDepartment);
		new Label(container, SWT.NONE);

		final Button btnQuery = new Button(container, SWT.NONE);
		btnQuery.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				pageControl = new PageControl(PAGE_SIZE);
				buildQueryConditions();
				pageQuery();
			}
		});
		btnQuery.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false));
		btnQuery.setText("查询");
		btnQuery.setImage(ImageManager.getImage(IImageKeys.SEARCH));

		final Button btnReset = new Button(container, SWT.NONE);
		btnReset.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				txtStudentName.setText("");
				comboCountry.deselectAll();
				txtContractNo.setText("");
				comboDepartment.deselectAll();
			}
		});
		final GridData gd_btnReset = new GridData(SWT.CENTER, SWT.CENTER, false, false);
		btnReset.setLayoutData(gd_btnReset);
		btnReset.setText("重置");
		btnReset.setImage(ImageManager.getImage(IImageKeys.RESET));

		final Label label_5 = new Label(container, SWT.NONE);
		label_5.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 4, 1));
		label_5.setFont(ResourceManager.getFont("", 10, SWT.BOLD));
		label_5.setText("查询结果:");
		
		new Label(container, SWT.NONE);
		new Label(container, SWT.NONE);
		
		lblResult = new Label(container, SWT.NONE);
		lblResult.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false));
		lblResult.setText("");

		lblPage = new Label(container, SWT.NONE);
		lblPage.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false));
		lblPage.setText("");		
		
		final Button btnFirstPage = new Button(container, SWT.NONE);
		btnFirstPage.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				if (pageControl == null) {
					MessageDialog.openInformation(e.display.getActiveShell(),
							IMessageKeys.FAIL, "请先进行查询!");
					return;
				}
				if (pageControl.getPageCount() > 0) {
					pageControl.setPageNo(1);
					pageQuery();
				}
			}
		});
		final GridData gd_btnFirstPage = new GridData(SWT.RIGHT, SWT.CENTER, false, false);
		btnFirstPage.setLayoutData(gd_btnFirstPage);
		btnFirstPage.setText("首页");
		btnFirstPage.setImage(ImageManager.getImage(IImageKeys.LEFT));

		final Button btnPrevPage = new Button(container, SWT.NONE);
		btnPrevPage.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				if (pageControl == null) {
					MessageDialog.openInformation(e.display.getActiveShell(),
							IMessageKeys.FAIL, "请先进行查询!");
					return;
				}
				if (pageControl.getPageNo() - 1 > 0) {
					pageControl.setPageNo(pageControl.getPageNo() - 1);
					pageQuery();
				}
			}
		});
		final GridData gd_btnPrevPage = new GridData(SWT.CENTER, SWT.CENTER, false, false);
		btnPrevPage.setLayoutData(gd_btnPrevPage);
		btnPrevPage.setText("上页");
		btnPrevPage.setImage(ImageManager.getImage(IImageKeys.UP));

		final Button btnNextPage = new Button(container, SWT.NONE);
		btnNextPage.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				if (pageControl == null) {
					MessageDialog.openInformation(e.display.getActiveShell(),
							IMessageKeys.FAIL, "请先进行查询!");
					return;
				}
				if (pageControl.getPageNo() + 1 <= pageControl.getPageCount()) {
					pageControl.setPageNo(pageControl.getPageNo() + 1);
					pageQuery();
				}
			}
		});
		btnNextPage.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false));
		btnNextPage.setText("下页");
		btnNextPage.setImage(ImageManager.getImage(IImageKeys.DOWN));

		final Button btnLastPage = new Button(container, SWT.NONE);
		btnLastPage.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				if (pageControl == null) {
					MessageDialog.openInformation(e.display.getActiveShell(),
							IMessageKeys.FAIL, "请先进行查询!");
					return;
				}
				if (pageControl.getPageCount() > 0) {
					pageControl.setPageNo(pageControl.getPageCount());
					pageQuery();
				}
			}
		});
		btnLastPage.setLayoutData(new GridData());
		btnLastPage.setText("尾页");
		btnLastPage.setImage(ImageManager.getImage(IImageKeys.RIGHT));		
		
		contractTableViewer = new TableViewer(container, SWT.FULL_SELECTION | SWT.BORDER);
		contractTableViewer.setLabelProvider(new TableLabelProvider());
		contractTableViewer.setContentProvider(new ContentProvider());
		contracts = contractTableViewer.getTable();
		contracts.addMouseListener(new MouseAdapter() {
			public void mouseDoubleClick(final MouseEvent e) {
			}
		});
		contracts.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				if (pageControl == null) {
					MessageDialog.openInformation(e.display.getActiveShell(),
							IMessageKeys.FAIL, "请先进行查询!");
					return;
				}
				IStructuredSelection selection = (IStructuredSelection) contractTableViewer
						.getSelection();
				OsDepartmentContract osDepartmentContract = (OsDepartmentContract) selection
						.getFirstElement();
				if (osDepartmentContract == null) {
					MessageDialog.openInformation(e.display.getActiveShell(),
							IMessageKeys.FAIL, "请先选择一条记录!");
				} else {
					OsDepartmentContractDialog dialog = new OsDepartmentContractDialog(
							getViewSite().getShell());
					dialog.setReadonly(true);
					dialog.setOsDepartmentContract(osDepartmentContract);
					dialog.open();
				}
			}
		});
		contracts.setLinesVisible(true);
		contracts.setHeaderVisible(true);
		final GridData gd_table = new GridData(SWT.FILL, SWT.FILL, true, true, 4, 1);
		gd_table.heightHint = 150;
		contracts.setLayoutData(gd_table);
		new Label(container, SWT.NONE);

		final Button btnView = new Button(container, SWT.NONE);
		btnView.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				if (pageControl == null) {
					MessageDialog.openInformation(e.display.getActiveShell(),
							IMessageKeys.FAIL, "请先进行查询!");
					return;
				}
				IStructuredSelection selection = (IStructuredSelection) contractTableViewer
						.getSelection();
				OsDepartmentContract osDepartmentContract = (OsDepartmentContract) selection
						.getFirstElement();
				if (osDepartmentContract == null) {
					MessageDialog.openInformation(e.display.getActiveShell(),
							IMessageKeys.FAIL, "请先选择一条记录!");
				} else {
					OsDepartmentContractDialog dialog = new OsDepartmentContractDialog(
							getViewSite().getShell());
					dialog.setReadonly(true);
					dialog.setOsDepartmentContract(osDepartmentContract);
					dialog.open();
				}
			}
		});
		final GridData gd_btnView = new GridData(SWT.CENTER, SWT.CENTER, false, false);
		btnView.setLayoutData(gd_btnView);
		btnView.setText("查看");
		btnView.setImage(ImageManager.getImage(IImageKeys.FORM));

		final Button btnAdd = new Button(container, SWT.NONE);
		btnAdd.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				OsDepartmentContractDialog dialog = new OsDepartmentContractDialog(
						getViewSite().getShell());
				dialog.setReadonly(false);
				if (dialog.open() == Window.OK) {
					pageControl = new PageControl(PAGE_SIZE);
					pageQuery();
				}
			}
		});
		btnAdd.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false));
		btnAdd.setText("部门签约");
		btnAdd.setImage(ImageManager.getImage(IImageKeys.SIGN));
		new Label(container, SWT.NONE);
		
		initializeTableViewer();
		initializeServices();
		setupValues();
		
		//
		createActions();
		initializeToolBar();
		initializeMenu();
	}
	
	public static final String CONTRACT_ID = "签约档案号";
	public static final String CONTRACT_NO = "合同号";
	public static final String STUDENT_NAME = "签约学生";
	public static final String COUNTRY_NAME = "咨询国家";
	public static final String DEPARTMENT_NAME = "部门";
	public static final String SIGNUP_SUM = "签约金额";
	public static final String LICENSE = "特许";
	public static final String SIGNUP_DATE = "签约日期";
	
	private void initializeTableViewer() {
		/*createSortedTableColumn(contractTableViewer, SWT.CENTER, CONTRACT_ID, "", 120,
				new ContractIdSorter(), SWT.UP, false, null).chooseColumnForSorting();*/
		createSortedTableColumn(contractTableViewer, SWT.CENTER, CONTRACT_NO, "", 100,
				new ContractNoSorter(), SWT.UP, false, null).chooseColumnForSorting();	
		createSortedTableColumn(contractTableViewer, SWT.CENTER, STUDENT_NAME, "", 120,
				new StudentNameSorter(), SWT.UP, false, null);
		createSortedTableColumn(contractTableViewer, SWT.CENTER, COUNTRY_NAME, "", 100,
				new CountryNameSorter(), SWT.UP, false, null);
		createSortedTableColumn(contractTableViewer, SWT.CENTER, DEPARTMENT_NAME, "", 100,
				new DepartmentNameSorter(), SWT.UP, false, null);
		createTableColumn(contractTableViewer, SWT.CENTER, SIGNUP_SUM, "", 100, null);
		createTableColumn(contractTableViewer, SWT.CENTER, LICENSE, "", 50, null);
		createSortedTableColumn(contractTableViewer, SWT.CENTER, SIGNUP_DATE, "", 170,
				new SignupDateSorter(), SWT.UP, false, null);
	}
	
	private DepartmentService departmentService;
	
	private OsDepartmentContractService osDepartmentContractService;
	
	private void initializeServices() {
		departmentService = (DepartmentService) SpringBeanFactory
				.getBean("departmentService");
		osDepartmentContractService = (OsDepartmentContractService) SpringBeanFactory
				.getBean("osDepartmentContractService");
	}
	
	List<Integer> countryIds = new ArrayList<Integer>();
	List<Integer> departmentIds = new ArrayList<Integer>();
	
	private void setupValues() {
		List<Country> countries = CountryCache.getInstance().getAllCountries();
		if (countries != null) {
			for (Country country : countries) {
				countryIds.add(country.getId());
				comboCountry.add(country.getName());
			}
		}
		List<Department> departments = departmentService.getAll();
		if (departments != null) {
			for (Department department : departments) {
				departmentIds.add(department.getId());
				comboDepartment.add(department.getName());
			}
		}
	}
	
	@SuppressWarnings("unchecked")
	private void buildQueryConditions() {
		conditions = new HashMap();
		if (StringUtils.isNotEmpty(txtStudentName.getText())) {
			conditions.put("studentName", txtStudentName.getText().trim());
		}
		if (comboCountry.getSelectionIndex() >= 0) {
			conditions.put("countryId", countryIds.get(comboCountry.getSelectionIndex()));
		}
		if (StringUtils.isNotEmpty(txtContractNo.getText())) {
			conditions.put("contractNo", txtContractNo.getText().trim());
		}
		if (comboDepartment.getSelectionIndex() >= 0) {
			conditions.put("departmentId", departmentIds.get(comboDepartment.getSelectionIndex()));
		}
	}
	
	private void pageQuery() {
		osDepartmentContractService.pageQuery(pageControl, conditions);
		contractTableViewer.setInput(pageControl.getPageData());
		lblResult.setText("查询结果共 " + pageControl.getRowCount() + " 条记录");
		lblPage.setText("页码(每页显示" + PAGE_SIZE + "条): " + pageControl.getPageNo() + "/" + pageControl.getPageCount());
		contracts.deselectAll();
	}
	
	/**
	 * Create the actions
	 */
	private void createActions() {
		// Create the actions
	}

	/**
	 * Initialize the toolbar
	 */
	private void initializeToolBar() {
	}

	/**
	 * Initialize the menu
	 */
	private void initializeMenu() {
	}

	@Override
	public void setFocus() {
		// Set the focus
	}
	
	// Convenience class which avoids casting in subclasses
	private abstract class AbstractSorter extends AbstractInvertableTableSorter {
		public int compare(Viewer viewer, Object o1, Object o2) {
			return compare((OsDepartmentContract) o1, (OsDepartmentContract) o2);
		}
		public abstract int compare(OsDepartmentContract c1, OsDepartmentContract c2);
	}
	/*private class ContractIdSorter extends AbstractSorter {
		public int compare(OsDepartmentContract c1, OsDepartmentContract c2) {
			return NumberUtils.compare(c1.getId(), c2.getId());
		}
	}*/
	private class ContractNoSorter extends AbstractSorter {
		public int compare(OsDepartmentContract c1, OsDepartmentContract c2) {
			return Collator.getInstance().compare(c1.getContractNo(),
					c2.getContractNo());
		}
	}
	private class StudentNameSorter extends AbstractSorter {
		public int compare(OsDepartmentContract c1, OsDepartmentContract c2) {
			return Collator.getInstance().compare(c1.getName(), c2.getName());
		}
	}
	private class CountryNameSorter extends AbstractSorter {
		public int compare(OsDepartmentContract c1, OsDepartmentContract c2) {
			return Collator.getInstance().compare(
					c1.getCountry().getName(),
					c2.getCountry().getName());
		}
	}
	private class DepartmentNameSorter extends AbstractSorter {
		public int compare(OsDepartmentContract c1, OsDepartmentContract c2) {
			return Collator.getInstance().compare(
					c1.getDepartment().getName(),
					c2.getDepartment().getName());
		}
	}
	private class SignupDateSorter extends AbstractSorter {
		public int compare(OsDepartmentContract c1, OsDepartmentContract c2) {
			return c1.getSignupDate().compareTo(c2.getSignupDate());
		}
	}

}
